/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012-2013 Oliver Katz */

#include "mod_share_server.h"

namespace sleepyface
{
    namespace arch
    {
        namespace modules
        {
        	ShareServer::ShareServer() : ArchModule()
        	{
        		setName("share-server");
        	}

        	int ShareServer::signal(ModuleSignal s, Architecture &a)
        	{
        		if (s.getCode() == signalInitialize)
        		{
	        		connection = z_ipc_server_init_global(s.getData(0).getInt());
	        		if (z_ipc_server_connect(&connection) != 0)
	        			return 1;
	        		server = z_share_server_init(&connection, s.getData(1).getInt());
	        		return 0;
	        	}
	        	else if (s.getCode() == signalUninitialize)
	        	{
	        		z_ipc_server_disconnect(&connection);
	        		z_ipc_server_release(connection);
	        		z_share_server_release(server);
	        		return 0;
	        	}
	        	else if (s.getCode() == signalShareVariableRW)
	        	{
	        		if (z_share_server_bind_rw(&server, s.getData(0).getInt(), (z_data *)s.getData(1).getData()) == NULL)
	        			return 1;
	        		return 0;
	        	}
	        	else if (s.getCode() == signalShareVariableRO)
	        	{
	        		if (z_share_server_bind_ro(&server, s.getData(0).getInt(), (z_data *)s.getData(1).getData()) == NULL)
	        			return 1;
	        		return 0;
	        	}
	        	else if (s.getCode() == signalRunForeground)
	        	{
	        		z_share_server_serve(&server);
	        		return 0;
	        	}
	        	else if (s.getCode() == signalRunBackground)
	        	{
	        		pid_t pid = fork();
	        		if (pid == 0)
	        		{
	        			z_share_server_serve(&server);
	        			_exit(0);
	        		}
	        		return 0;
	        	}
	        	else
	        	{
	        		return 0;
	        	}
        	}
		}
	}
}
